package cn.jofei.netty.hadler;

import cn.jofei.common.netty.handler.RelayHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WebSocketHandShakeHandler
 *
 * @author Jofei Bao
 * @version ngbao v1.0.2
 * @date 2022年10月17日 23:03
 */
@Data
public class WebSocketHandShakeHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(WebSocketHandShakeHandler.class);

    private WebSocketClientHandshaker clientShaker;
    private Channel cChannel;
    private Channel rChannel;

    public WebSocketHandShakeHandler(WebSocketClientHandshaker clientShaker, Channel cChannel, Channel rChannel) {
        this.clientShaker = clientShaker;
        this.cChannel = cChannel;
        this.rChannel = rChannel;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.channel().config().setAutoRead(false);
        if (!clientShaker.isHandshakeComplete()) {
            try {
                clientShaker.finishHandshake(cChannel, (FullHttpResponse) msg);
                logger.info("websocket Handshake 完成!");
            } catch (WebSocketHandshakeException e) {
                logger.info("websocket连接失败!");
            }
        }
        cChannel.config().setAutoRead(false);

//        cChannel.pipeline().remove("ws-decoder");
//        cChannel.pipeline().remove("ws-encoder");
        cChannel.pipeline().addLast(new RelayHandler(rChannel));

//        rChannel.pipeline().remove("wsdecoder");
//        rChannel.pipeline().remove("wsencoder");
        rChannel.pipeline().addLast(new RelayHandler(cChannel));

        rChannel.config().setAutoRead(true);
        cChannel.config().setAutoRead(true);

        cChannel.pipeline().remove(this);
        ctx.channel().config().setAutoRead(true);
    }
}
